package com.fengye.serialization.serializer.impl;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import com.fengye.serialization.serializer.Serializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * @Author fengye
 * @Date 2023/2/12 17:36
 **/
public class HessianSerializer implements Serializer {
    @Override
    public <T> byte[] serialize(T obj) throws Exception {
        if(obj ==  null) {
            return new byte[0];
        }

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        HessianOutput hessianOutput = new HessianOutput(byteArrayOutputStream);
        hessianOutput.writeObject(obj);

        byte[] bytes = byteArrayOutputStream.toByteArray();

        hessianOutput.close();
        byteArrayOutputStream.close();
        return bytes;
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) throws Exception {
        if(data == null) {
            return null;
        }

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
        HessianInput hessianInput = new HessianInput(byteArrayInputStream);

        T obj = (T)hessianInput.readObject();

        hessianInput.close();
        byteArrayInputStream.close();

        return obj;
    }
}
